package com.java.sevice;

import com.alibaba.fastjson.JSONObject;
import com.java.dto.ResultMsg;
import com.java.remoteInterface.Bank1Service;
import com.java.remoteInterface.Bank2Service;
import lombok.extern.slf4j.Slf4j;
import org.apache.servicecomb.saga.omega.context.annotations.SagaStart;
import org.apache.servicecomb.saga.omega.transaction.annotations.Compensable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
@Slf4j
public class TransferService {
    @Autowired
    Bank1Service bank1Service;
    @Autowired
    Bank2Service bank2Service;

    /**
     * 转账
     *
     * @param accountId 用户账户
     * @param amount    转账金额
     *                  <p>
     *                  SagaStart 单位是秒，源码里面有备注
     */
    @SagaStart(timeout = 5)
    @Transactional(rollbackFor = Exception.class)
    @Compensable(timeout = 5, compensationMethod = "cancelTransfer")
    public ResultMsg transferMoney(Long accountId, BigDecimal amount) {
        log.info("transfer-service 转账开始");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("accountId", accountId);
        jsonObject.put("amount", amount);
        bank1Service.doTransfer(jsonObject);
        bank2Service.doTransfer(jsonObject);
        return ResultMsg.ok("成功");
    }

    public ResultMsg cancelTransfer(Long accountId, BigDecimal amount) {
        log.info("transfer-service 转账取消");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("accountId", accountId);
        jsonObject.put("amount", amount);
        bank1Service.cancelTransfer(jsonObject);
        bank2Service.cancelTransfer(jsonObject);
        return ResultMsg.ok("成功");
    }
}